package org.example.DesignPatterns.Memento;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: farprt
 * @create: 2022-09-23 18:47
 **/
public class Editor {

    private Doc doc;
    private List<History> historieRecords;
    private int historyPosition=-1;

    public Editor(Doc doc) {
        System.out.println("打开文档"+doc.getTitle());
        this.doc = doc;
        historieRecords=new ArrayList<>();
        backup();//载入文档后保存第一份历史记录
        show();//显示内容
    }

    public void append(String txt){
        System.out.println("<<<插入操作");
        doc.setBody(doc.getBody()+txt);
        backup();
        show();
    }

    public void save(){
        System.out.println("存盘操作<<<");
    }

    public void delete(){
        System.out.println("<<<删除操作");
        doc.setBody("");
        backup();
        show();
    }

    private void backup(){
        historieRecords.add(doc.createHistory());
        historyPosition++;
    }

    private void show(){
        System.out.println(doc.getBody());
        System.out.println("文档结束>>>");
    }

    //撤销操作
    public void undo(){
        System.out.println(">>>撤销操作");
        if(historyPosition==0){
            return;
        }
        historyPosition--;
        History history=historieRecords.get(historyPosition);
        doc.restoreHistory(history);//取出历史记录并恢复至文档
        show();
    }

    public void redo(){
        System.out.println("重做操作");
        if(historyPosition==0 || historyPosition>=historieRecords.size()){
            return;
        }
        historyPosition++;
        History history=historieRecords.get(historyPosition);
        doc.restoreHistory(history);
        show();

    }




}